package com.aidex.biz.smy.utils;

import com.aidex.biz.smy.bo.ClientBaseConfig;
import com.aidex.biz.smy.vo.BaseVO;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;

import java.util.Map;
import java.util.UUID;

@Slf4j
public class NormalEncryptionUtil {


    //固定加密版本号
    private static final String encryptionVersion = "3.1";


    //响应参数加密 加签
    public static BaseVO requestEncryption(String bizContent, ClientBaseConfig baseConfig, String version) {
        // 生产时请向我司索取正式商户号
        BaseVO result = new BaseVO();
        result.setVersion(version);
        if (encryptionVersion.equals(version)) {
            //生成业务报文加密秘钥
            String bizKey = DigestUtils.md5Hex(UUID.randomUUID().toString().replaceAll("-", "")).substring(0, 16);
            //加密公钥
            String aesSecretKey = RSASignUtil.encryptSignPubKey(bizKey, baseConfig.getSmyPublicKey());
            result.setSecretKey(aesSecretKey);

            //加密业务字段
            bizContent = AESUtil.strEncodBase64(bizKey, bizContent.trim());
        }
        result.setBizContent(bizContent);
        Map<String, String> param = MapUtils.objectToMap(result);
        //生成待签名字符串
        String requestParam = RSASignUtil.getSortString(param);
        // 用排序的参数字符串构造MD5摘要
        String md5 = DigestUtils.md5Hex(requestParam);
        //生成签名串
        String createSign = RSASignUtil.encryptSign(md5, baseConfig.getOwnerPrivateKey());
        result.setSign(createSign);
        return result;
    }

    //请求参数解密 验签
    public static String responseDecrypt(String responseStr, ClientBaseConfig baseConfig) {

        Map<String, String> responseMap = JSON.parseObject(responseStr, Map.class);
        String reSign = responseMap.get("sign");
        responseMap.remove("sign");
        String reTurnMd5 = DigestUtils.md5Hex(RSASignUtil.getSortString(responseMap));
        if (reTurnMd5.equals(RSASignUtil.decryptSign(reSign, baseConfig.getSmyPublicKey()))) {
            log.info("响应签名通过");
        } else {
            log.warn("响应签名不通过");
        }
        //解密响应
        String resBody = responseMap.get("bizContent");
        if (encryptionVersion.equals(responseMap.get("version"))) {
            String aesSecretKey = RSASignUtil.decryptSignPriKey(responseMap.get("secretKey"),
                    baseConfig.getOwnerPrivateKey());
            resBody = AESUtil.base64StrDecode(aesSecretKey, resBody);
        }
        log.info("结果值:{}", resBody);
        return resBody;
    }

}
